<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: liguohua@clcw.com.cn  Blog:http://blog.sina.com.cn/saverneo        |
// +------------------------------------------------------------------------+
//
//用户登录
namespace AuctionAppApi\Controller;

use Think\Controller;
use AuctionCore\System\AuctionException;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\Common\PhpRedis;
use AuctionCore\CarResource\CarReport;
use AuctionCore\AuctionOrder\Scene;
use AuctionCore\CarResource\CarModel;
use Services\AuctionService\inParamsBidding;

//weaver 客户端 START-----------------------
require_once MODULE_PATH . 'Org/Thrift/Lib/Thrift/ClassLoader/ThriftClassLoader.php';

use Services\AuctionService\AuctionServiceClient;
use Thrift\ClassLoader\ThriftClassLoader;

$loader = new ThriftClassLoader();
$loader->registerNamespace('Thrift', MODULE_PATH . 'Org/Thrift/Lib');
$loader->registerDefinition('Services', MODULE_PATH . 'Org/Thrift/gen-php');
$loader->register();

use Thrift\Protocol\TBinaryProtocol;
use Thrift\Protocol\TMultiplexedProtocol;
use Thrift\Transport\THttpClient;
use Thrift\Transport\TBufferedTransport;
use Thrift\Exception\TException;
use AuctionCore\System\SystemConf;

//weaver 客户端 END-----------------------

/**
 * 拍单接口
 */
class OrderController extends BaseController {
        public $h5_actions = array('C_ORDER|A_DETAIL','C_ORDER|A_FOLLOW');
        public $report = null;
        public $coupon_limit = null;
        public function __construct(){
            parent::__construct();
            if(!$this->order_id){
                AuctionException::make_throw('700027');
            }
            $coupon_limit = SystemConf::getConfByName('COUPON_LIMIT');
            $this->coupon_limit = $coupon_limit['value'];
            $this->redis = new PhpRedis();
        }
        public function index(){
        }

        /**
         * 投标、待竞拍，竞拍，待确认、 公共页面内容数据 (for 新版本 ，原生展示)
         */
        public function public_data_v100($order){
                $order_info = $order->detail();
                //获取车辆检测报告
                $this->report = new CarReport($order_info['car_id']);
                $title = $this->title();
                $head = array();
                $head['status'] = $order_info['status'];
                $head['dealer_id'] = $this->dealer_id;
                $head['model_show'] = $title['clcw_app_model_show'];
                foreach($this->report->report['pictures'] as $pic){
                      if($pic['pic_key']=='p_left_front45'){
                         $head['car_pic'] = $pic['pic_url'].'';
                          break;
                      }
                }
                $head['composite_state'] = $title['composite_state'];
                $head['acc_level'] = $title['acc_level'];
                $head['acc_level_desc'] = C('ACC_LEVEL_DESC');
                $head['composite_state_desc'] = C('COMPOSITE_STATE_DESC');
                $head['order_id'] = $order_info['order_id'];
                $head['order_no'] = $order_info['order_no'];
                $head['car_id'] = $order_info['car_id'];
                $head['car_no'] = $title['car_no'];
                $head['first_reg_date'] = date('Y年m月',strtotime($this->report->report['car_base']['first_reg_date']));
                //投标最高价
                $head['bid_best_price'] = $order_info['bid_best_price'];
                $head['bid_best_price_show'] = strip_tags(format_money($order_info['bidding_best_price']));//显示价格
                //竞拍最高价
                $head['bidding_best_price'] = $order_info['bidding_best_price'];
                $head['bidding_best_price_show'] = strip_tags(format_money($order_info['bidding_best_price']));//显示价格
                //拍单最高价
                $head['best_price'] = strip_tags(format_money($order_info['bidding_best_price']>$order_info['bid_best_price']?$order_info['bidding_best_price']:$order_info['bid_best_price']));
                //起拍价
                $head['bid_start_price'] = $order_info['bid_start_price'];
                $head['bid_start_price_show'] = strip_tags(format_money($order_info['bid_start_price']));
                //保留价
                $reserve_price = $order_info['reserve_price'];
                if($reserve_price>=10000){
                    $reserve_price = strip_tags(format_money($reserve_price));
                }
                $head['reserve_price'] = $reserve_price;
                $head['show_reserve_price'] = $order_info['show_reserve_price']?true:false;
                //佣金
                $head['commision'] = $order_info['commision'];
                //交付服务费
                $head['transfer_fee'] = $order_info['transfer_fee'];
                //是否定时单
                $head['is_timing_order'] = $order_info['is_timing_order'];
                //竞标开始时间
                $head['bidding_start_time'] = $order_info['bidding_start_time'];
                //竞拍结束时间
                $head['bidding_end_time'] = $order_info['bidding_end_time'];
                $head['bidding_end_time_show'] = date('Y年m月d日 H时i分',strtotime($order_info['bidding_end_time']));//转换为 年月日时分
                //场次信息
                $scene = new Scene();
                $sc = $scene->detail($order_info['scene_id']);
                $head['scene_starttime'] = $sc['starttime'];
                $head['scene_id'] = $order_info['scene_id'];
                $head['rank'] = $order_info['rank'];
                $head['coupon'] = $order_info['coupon'];
                $head['pointer_mileage'] = convert_mileage($this->report->report['car_base']['pointer_mileage']);
                //车牌号
                $head['plate'] = C('PLATE_PREFIX.'.$this->report->report['car_base']['plate_prefix']).substr($this->report->report['car_base']['plate_suffix'],0,1);
                //过户限制
                $head['transfer_limit'] = C('TRANSFER_LIMIT.'.$this->report->report['car_base']['transfer_limit']);
                //参与竞价车商人数统计、出价次数统计
                $head['dealer_num'] = $order->stat_bidding_dealer();
                $head['bid_num'] = $order->stat_bidding_price();
                //
                $head['emission'] = C('EMISSION.'.$this->report->report['car_base']['emission']);
                //您未对此车出价！| 您的最高出价：8.28万（投标）
                $dealer = new Dealer($this->dealer_id);
                $head['my_highest_price'] = $dealer->get_my_highest_price($this->order_id);//array('bid','80200')|array('bidding','98000')
                $head['my_highest_price'][1] = strip_tags(format_money($head['my_highest_price'][1]));
                //是否已关注
                $head['is_followed'] = $dealer->is_followed($this->order_id)?true:false;

                $head['report']['title'] = $title;
                $head['report']['base_info'] = $this->base_info();
                $head['report']['procedure'] = $this->procedure();
                $head['report']['config'] = $this->config();
                $head['report']['perform'] = $this->perform();
                $head['report']['base_pics'] = $this->base_pics();

                //隐性损伤文字描述
                $head['report']['hidden']['frame'] = $this->report->frame_history_v100();
                $head['report']['hidden']['appear'] = $this->report->appear_history_v100();
                //隐性损伤图片
                $head['report']['hidden']['frame']['pic'] = $title['damage_pics']['hidden']['frame'];
                $head['report']['hidden']['appear']['pic'] = $title['damage_pics']['hidden']['outside'];

                //显性损伤文字描述
                $desc = $this->report->get_dm_describe();
                $head['report']['visible']['frame'] = $desc['frame']?$desc['frame']:array();
                $head['report']['visible']['outside'] = $desc['outside']?$desc['outside']:array();
                $head['report']['visible']['inside'] = $desc['inside']?$desc['inside']:array();
                //显性损伤图片
                $head['report']['visible']['frame']['pic'] = $title['damage_pics']['visible']['frame'];
                $head['report']['visible']['outside']['pic'] = $title['damage_pics']['visible']['outside'];
                $head['report']['visible']['inside']['pic'] = $title['damage_pics']['visible']['inside'];

                //轻微，一般，严重
                $degree = $this->get_dm_by_degree();

                $head['report']['degree']['light'] = $degree['light']?$degree['light']:array();
                $head['report']['degree']['normal'] = $degree['normal']?$degree['normal']:array();
                $head['report']['degree']['serious'] = $degree['serious']?$degree['serious']:array();

                return $head;
        }

        /**
         * 投标、待竞拍，竞拍，待确认、 公共页面内容数据 (for 新版本 ，原生展示)
         */
        public function public_data_v130($order){
                $order_info = $order->detail();
                //获取车辆检测报告
                $this->report = new CarReport($order_info['car_id']);
                $title = $this->title();
                $head = array();

                $head['dealer_id'] = $this->dealer_id;
                $head['model_show'] = $title['clcw_app_model_show'];
                foreach($this->report->report['pictures'] as $pic){
                      if($pic['pic_key']=='p_left_front45'){
                         $head['car_pic'] = get_content_cdnurl().$pic['pic_url'].'';
                          break;
                      }
                }
                $head['composite_state'] = $title['composite_state'];
                $head['acc_level'] = $title['acc_level'];
//                $head['acc_level_desc'] = C('ACC_LEVEL_DESC');
//                $head['composite_state_desc'] = C('COMPOSITE_STATE_DESC');
                $head['order_id'] = $order_info['order_id'];
                $head['order_no'] = $order_info['order_no'];
                //
                $head['status'] = $order_info['status'];
                switch($order_info['status']){
                    case '3':$head['status_cn'] = '投标中';break;
                    case '301':$head['status_cn'] = '待竞拍';break;
                    case '4':$head['status_cn'] = '竞拍中';break;
                    case '5':$head['status_cn'] = '待确认';break;
                }

                //是否能用代金券
                $head['use_coupon'] = $order_info['coupon'] > 0 ? true : false;
                if($order_info['coupon'] > 0){
                    $head['coupon_string'] = "拍卖最高价大于等于".$this->coupon_limit."时可用代金券".$order_info['coupon']."元";
                }
                //查看是否智能出价
                $redis = new PhpRedis();
                $arr = ['order_id'=>$order_info['order_id']];
                $key1 = getRedisKeyByCode('REDIS_KEY','100008',$arr);
                $zhi_list = $redis->zrange($key1,0,-1);
                if(in_array($this->dealer_id,$zhi_list)){
                    $head['is_auto_bidding'] = true; //增加智能报价标签
                }else{
                    $head['is_auto_bidding'] = false;
                }
                $head['car_id'] = $order_info['car_id'];
                $head['car_no'] = $title['car_no'];
                $head['first_reg_date'] = date('Y年m月',strtotime($this->report->report['car_base']['first_reg_date']));
                //投标最高价
                $head['bid_best_price'] = $order_info['bid_best_price'];
                $head['bid_best_price_show'] = strip_tags(format_money($order_info['bidding_best_price']));//显示价格
                //竞拍最高价
                $head['bidding_best_price'] = $order_info['bidding_best_price'];
                $head['bidding_best_price_show'] = strip_tags(format_money($order_info['bidding_best_price']));//显示价格
                //拍单最高价
                $head['best_price'] = strip_tags(format_money($order_info['bidding_best_price']>$order_info['bid_best_price']?$order_info['bidding_best_price']:$order_info['bid_best_price']));
                //起拍价
                $head['bid_start_price'] = $order_info['bid_start_price'];
                $head['bid_start_price_show'] = strip_tags(format_money($order_info['bid_start_price']));
                //保留价
                $reserve_price = $order_info['reserve_price'];
                if($reserve_price>=10000){
                    $reserve_price = strip_tags(format_money($reserve_price));
                }
                $head['reserve_price'] = $reserve_price;
                $head['show_reserve_price'] = $order_info['show_reserve_price']?true:false;
                //佣金
                $head['commision'] = $order_info['commision'];
                //交付服务费
                $head['transfer_fee'] = $order_info['transfer_fee'];
                //是否定时单
                $head['is_timing_order'] = $order_info['is_timing_order'];
                //竞标开始时间
                //$head['bidding_start_time'] = $order_info['bidding_start_time'];
                $head['bidding_start_time'] = strtotime($order_info['bidding_start_time'])*1000;
                //竞拍结束时间
                $head['bidding_end_time'] = $order_info['bidding_end_time'];
                $head['bidding_end_time_show'] = date('Y年m月d日 H时i分',strtotime($order_info['bidding_end_time']));//转换为 年月日时分

                //结束时间（竞拍结束时间、投标结束时间 时间戳）
                $head['act_elapsed_time'] = $order_info['act_elapsed_time']*1000;
                $head['est_elapsed_time'] = $order_info['est_elapsed_time']*1000;

                //场次信息
                $scene = new Scene();
                $sc = $scene->detail($order_info['scene_id']);
                $head['scene_starttime'] = $sc['starttime'];
                $head['starttime'] = strtotime($sc['starttime'])*1000;

                $head['scene_id'] = $order_info['scene_id'];
                $head['rank'] = $order_info['rank'];
                $head['coupon'] = $order_info['coupon'];
                $head['pointer_mileage'] = convert_mileage($this->report->report['car_base']['pointer_mileage']);
                //车牌号
                $head['plate'] = C('PLATE_PREFIX.'.$this->report->report['car_base']['plate_prefix']).substr($this->report->report['car_base']['plate_suffix'],0,1);
                //过户限制
                $head['transfer_limit'] = C('TRANSFER_LIMIT.'.$this->report->report['car_base']['transfer_limit']);
                //参与竞价车商人数统计、出价次数统计
                $head['dealer_num'] = $order->stat_bidding_dealer();
                $head['bid_num'] = $order->stat_bidding_price();
                //
                $head['emission'] = C('EMISSION.'.$this->report->report['car_base']['emission']);
                //您未对此车出价！| 您的最高出价：8.28万（投标）
                $dealer = new Dealer($this->dealer_id);
                $head['my_highest_price'] = $dealer->get_my_highest_price($this->order_id);//array('bid','80200')|array('bidding','98000')
                $head['my_highest_price'][1] = strip_tags(format_money($head['my_highest_price'][1]));
                //是否已关注
                $head['is_followed'] = $dealer->is_followed($this->order_id)?true:false;

                $head['report']['title'] = $title;
                $head['report']['base_info'] = $this->base_info();
                $head['report']['procedure'] = $this->procedure();
                $head['report']['config'] = $this->config();
                $head['report']['perform'] = $this->perform();
                $head['report']['base_pics'] = $this->base_pics();

                //隐性损伤文字描述
                $head['report']['hidden']['frame'] = $this->report->frame_history_v100();
                $head['report']['hidden']['appear'] = $this->report->appear_history_v100();
                //隐性损伤图片
                $head['report']['hidden']['frame']['pic'] = $title['damage_pics']['hidden']['frame'];
                $head['report']['hidden']['appear']['pic'] = $title['damage_pics']['hidden']['outside'];

                //显性损伤文字描述
                $desc = $this->report->get_dm_describe();
                $head['report']['visible']['frame'] = $desc['frame']?$desc['frame']:array();
                $head['report']['visible']['outside'] = $desc['outside']?$desc['outside']:array();
                $head['report']['visible']['inside'] = $desc['inside']?$desc['inside']:array();
                //显性损伤图片
                $head['report']['visible']['frame']['pic'] = $title['damage_pics']['visible']['frame'];
                $head['report']['visible']['outside']['pic'] = $title['damage_pics']['visible']['outside'];
                $head['report']['visible']['inside']['pic'] = $title['damage_pics']['visible']['inside'];

                //轻微，一般，严重
                $degree = $this->get_dm_by_degree();

                $head['report']['degree']['light'] = $degree['light']?$degree['light']:array();
                $head['report']['degree']['normal'] = $degree['normal']?$degree['normal']:array();
                $head['report']['degree']['serious'] = $degree['serious']?$degree['serious']:array();

                //报告分享
                $short_param = short_url($order_info['order_id']);
                $arr = ['shorturl'=>$short_param];
                $keyName = getRedisKeyByCode('REDIS_KEY','100009',$arr);

                $is_short_param = $this->redis->get($keyName);
                if(!$is_short_param){
                    $this->redis->set($keyName, $order_info['order_id'], 60 * 60 * 24 * 7);
                }
                $share_url =  "http://cdn.lpaiche.com/lpcapp" . U("Share/report", ['params'=>$short_param]);
                $head['report']['share'] = array(
                    'title' => $head['model_show'],
                    'url'   => $share_url,
                    'desc'  => $title['desc'],
                    'image' => $head['car_pic']
                );

                return $head;
        }

        /**
         * 投标、等待竞标、竞标、待确认页面展示(for新版本，原生展示)
         */
        public function detail_native(){
                    $order = new AuOrder($this->order_id);
                    $detail = $order->detail();
                    switch($detail['status']){
                        case '3'://投标中
                                $this->bid_v100($order);
                            break;
                        case '301'://等待竞标
                                $this->bidding_v100($order,'301');
                            break;
                        case '4'://竞拍中
                                $this->bidding_v100($order);
                            break;
                        default://待确认
                            $this->bidding_finish_v100($order);
                            break;
                    }
            }
        /**
         * 投标、等待竞标、竞标、待确认页面展示(for新版本，原生展示)
         */
        public function detail_native_v130(){
                    $order = new AuOrder($this->order_id);
                    $detail = $order->detail();
                    switch($detail['status']){
                        case '3'://投标中
                                $this->bid_v130($order);
                            break;
                        case '301'://等待竞标
                                $this->bidding_v130($order,'301');
                            break;
                        case '4'://竞拍中
                                $this->bidding_v130($order);
                            break;
                        default://待确认
                            $this->bidding_finish_v130($order);
                            break;
                    }
            }

        //----------------------------新版本，页面原生展示
        /**
         * 投标出价页面展示(原生展示)
         * @param $order
         */
        private function bid_v100($order){
                $public_data = $this->public_data_v100($order);
                //倒计时
                $t = strtotime($public_data['scene_starttime'])-time();
                $public_data['time_to_end_bid']=format_second($t+2);//初始化倒计时
                $public_data['left_time']=$t+2;//倒计时基数
                if(date('d')==date('d',strtotime($public_data['scene_starttime']))){
                    $str = '今日';
                }elseif(date('d',strtotime('+1 day'))==date('d',strtotime($public_data['scene_starttime']))){
                    $str = '明日';
                }
                $public_data['bidding_start_time'] = $str.date('H:i',strtotime($public_data['scene_starttime']));//本拍单竞标开始时间

                //最后投标价
                $dealer = new Dealer($this->dealer_id);
                $my_last_bid_price = $dealer->get_my_last_bid_price($public_data['order_id']);
                $my_last_bid_price_show = $my_last_bid_price;

                //交易服务费
                $public_data['commision'] = $my_last_bid_price>0? get_commision($my_last_bid_price,$public_data['scene_starttime']):get_commision($public_data['bid_start_price'],$public_data['scene_starttime']);

                //json
                $public_data['my_last_bid_price'] = floatval($my_last_bid_price_show);
                $public_data['my_last_bid_price_show'] = strip_tags(format_money($my_last_bid_price_show));
                $this->api_200($public_data);
        }

        /**
        *竞标出价页面展示(原生展示)
        */
        private function bidding_v100($order,$status='4'){
                $public_data = $this->public_data_v100($order);

                if($status=='301'){
                    //获取开始时间(等待竞标拍单用)
                    $timestamp=strtotime($public_data['bidding_start_time']);
                    //拍单开始时间
                    $public_data['bidding_start_time'] = date('H:i',$timestamp);
                    //拍单开始倒计时
                    $public_data['left_time'] = $timestamp-time()+2;
                }
                //交易服务费
                $public_data['commision'] = get_commision($public_data['bidding_best_price']>0? $public_data['bidding_best_price']:$public_data['bid_start_price']);

                //json
                $public_data['status'] = $status;
                $public_data['bidding_info'] = json_encode($order->get_bidding_info(),true);
                $public_data['dealer_id'] = $this->dealer_id;
                $this->api_200($public_data);
        }
        /*
         * 待确认页面展示(原生展示)
         * */
        private  function bidding_finish_v100($order,$status='5'){
                $public_data = $this->public_data_v100($order);
                $order = new AuOrder($this->order_id);
                $bidding_price_log = $this->get_bidding_price_log(true,4);

                //本次拍卖最高价
                $public_data['au_best_price'] = '本次拍卖最高价：'.$public_data['best_price'].'元（'.($public_data['bidding_best_price'] > $public_data['bid_best_price']?'竞拍':'投标').'）';
                //您的最高出价
                $public_data['my_best_price'] = $public_data['my_highest_price'] > 0? '您的最高出价：'.$public_data['my_highest_price'][1].'元（'.($public_data['my_highest_price'][0] == 'bidding' ? '竞标':'投标').'）':'您未对此车出价！';


                //下一个拍品
                $next = array();
                $res = $order->get_next();
                if($res){
                    $cm = new CarModel();
                    $series = $cm->get_model_by_id($res['series_id'],'series');
                    //
                    $next['order_id'] = $res['order_id'];
                    $next['order_no'] = $res['order_no'];
                    $next['model_show_next'] = $series['name'].' '.$res['car_cc'].($res['turbo']?'T':'L').' '.C('GEARBOX.'.$res['gearbox']);
                    $next['url'] = APP_URL.'Order/detail_native/order_id/'.$next['order_id'];
                }

                //json
                $public_data['bidding_price_log'] = $bidding_price_log;
                $public_data['status'] = $status;
                $public_data['next'] = $next;

                $this->api_200($public_data);
        }

        //----------------------------新版本v130
        /**
         * 投标出价页面展示(原生展示)
         * @param $order
         */
        private function bid_v130($order){
                $public_data = $this->public_data_v130($order);

                //最后投标价
                $dealer = new Dealer($this->dealer_id);
                $my_last_bid_price = $dealer->get_my_last_bid_price($public_data['order_id']);
                $my_last_bid_price_show = $my_last_bid_price;

                //交易服务费
                $public_data['commision'] = $my_last_bid_price>0? get_commision($my_last_bid_price,$public_data['scene_starttime']):get_commision($public_data['bid_start_price'],$public_data['scene_starttime']);

                //json
                $public_data['my_last_bid_price'] = floatval($my_last_bid_price_show);
                $public_data['my_last_bid_price_show'] = strip_tags(format_money($my_last_bid_price_show));
                $this->api_200($public_data);
        }

        /**
        *竞标出价页面展示(原生展示)
        */
        private function bidding_v130($order,$status='4'){
                $public_data = $this->public_data_v130($order);
                $dObj = new Dealer($this->dealer_id);
                $my_last_bidding_price = $dObj->get_my_last_bidding_price($public_data['order_id']);
                $public_data['my_last_bidding_price'] = floatval($my_last_bidding_price);

                //交易服务费
                $public_data['commision'] = get_commision($public_data['bidding_best_price']>0? $public_data['bidding_best_price']:$public_data['bid_start_price']);

                //json
                $public_data['status'] = $status;
                $public_data['bidding_info'] = json_encode($order->get_bidding_info(),true);
                $public_data['dealer_id'] = $this->dealer_id;

                $this->api_200($public_data);
        }
        /*
         * 待确认页面展示(原生展示)
         * */
        private  function bidding_finish_v130($order,$status='5'){
                $public_data = $this->public_data_v130($order);
                $order = new AuOrder($this->order_id);
                $bidding_price_log = $this->get_bidding_price_log(true,4);

                //本次拍卖最高价
                $public_data['au_best_price'] = '本次拍卖最高价：'.$public_data['best_price'].'元（'.($public_data['bidding_best_price'] > $public_data['bid_best_price']?'竞拍':'投标').'）';
                //您的最高出价
                $public_data['my_best_price'] = $public_data['my_highest_price'] > 0? '您的最高出价：'.$public_data['my_highest_price'][1].'元（'.($public_data['my_highest_price'][0] == 'bidding' ? '竞标':'投标').'）':'您未对此车出价！';


                //下一个拍品
                $next = array();
                $res = $order->get_next();
                if($res){
                    $cm = new CarModel();
                    $series = $cm->get_model_by_id($res['series_id'],'series');
                    //
                    $next['order_id'] = $res['order_id'];
                    $next['order_no'] = $res['order_no'];
                    $next['model_show_next'] = $series['name'].' '.$res['car_cc'].($res['turbo']?'T':'L').' '.C('GEARBOX.'.$res['gearbox']);
                    $next['url'] = APP_URL.'Order/detail_native/order_id/'.$next['order_id'];
                }

                //json
                $public_data['bidding_price_log'] = $bidding_price_log;
                $public_data['status'] = $status;
                $public_data['next'] = $next;

                $this->api_200($public_data);
        }

        //------------------------------------
        /**
        *保存投标出价
        */
        public function save_bid(){
                $dealer_id = $this->dealer_id;
                $order_id = $this->order_id;
                $price = I('post.price');

                //数据验证
                if(!$dealer_id){
                    AuctionException::make_throw('500001');
                }
                if(intval($price)<=0){
                    AuctionException::make_throw('700034');
                }
                if(abs($price)%100>0){
                    AuctionException::make_throw('700035');
                }
                if(strlen(abs($price))>7){
                    AuctionException::make_throw('700036');
                }
                //
                $dev_type = $this->is_ios ? 2 :1;//出价设备

                try {
                    $handle = new THttpClient(C('WEAVER_URL'), 80, '/Auction/run');
                    $transport = new TBufferedTransport($handle);
                    $protocol = new TBinaryProtocol($transport);
                    $auctionProtocol = new TMultiplexedProtocol($protocol, 'AuctionService');
                    $auctionService = new AuctionServiceClient($auctionProtocol);

                    $res = $auctionService->bid($dealer_id,$order_id, $price,$dev_type);
                    if($res->code!='200') {
                        AuctionException::make_throw($res->code,$res->message);
                    }
                } catch (TException $tx) {
                    $code = $tx->getCode();
                    $msg = $tx->getMessage();
                    AuctionException::make_throw($code,$msg);
                }

                //输出json数据
                $data = array();
                $scene = new Scene();
                $order = new AuOrder($order_id);
                $order_info = $order->detail();
                $sc = $scene->detail($order_info['scene_id']);
                $data['commision'] = get_commision($price,$sc['starttime']);
                $data['transfer_fee'] = $order_info['transfer_fee'];

                $this->api_200($data);
                exit;
        }

        /**
        *保存竞标出价
        */
        public function bidding_price(){

            $dealer_id = $this->dealer_id;
            $order_id = $this->order_id;

            $base_price = I('post.base_price');
            $add_price = I('post.add_price');

            //数据验证
            if(!$dealer_id){
                AuctionException::make_throw('500001');
            }
            if(intval($base_price)<=0){
                AuctionException::make_throw('700038');
            }
            if(intval($add_price)<=0){
                AuctionException::make_throw('700039');
            }
            if(strlen(abs($add_price))>7){
                AuctionException::make_throw('700040');
            }
            $dev_type = ($this->is_ios?2:1);

            $data = array();
            try {
                $handle = new THttpClient(C('WEAVER_URL'), 80, '/Auction/run');
                $transport = new TBufferedTransport($handle);
                $protocol = new TBinaryProtocol($transport);
                $auctionProtocol = new TMultiplexedProtocol($protocol, 'AuctionService');
                $auctionService = new AuctionServiceClient($auctionProtocol);

                $InParamsBidding                = new InParamsBidding();
                $InParamsBidding->dealerId      = $dealer_id;
                $InParamsBidding->orderId       = $order_id;
                $InParamsBidding->basePrice     = $base_price;
                $InParamsBidding->addPrice      = $add_price;
                $InParamsBidding->price         = 0;
                $InParamsBidding->deviceType    = $dev_type;
                $InParamsBidding->isAuto        = 0;

                $res = $auctionService->bidding($InParamsBidding);//return bool
                if(!$res){
                    $msg = '竞拍出价失败:order_id:'.$order_id.' dealer_id:'.$dealer_id.' base_price:'.$base_price.' add_price:'.$add_price;
                    trace($msg,'','DEBUG',true);
                    AuctionException::make_throw(700049);
                }
            } catch (TException $tx) {
                $code = $tx->getCode();
                $msg = $tx->getMessage();
                if($code == '700008'){
                    $order = new AuOrder($order_id);
                    $order->thorw_to_app($dealer_id);
                }else{
                    AuctionException::make_throw($code,$msg);
                }
            }

            //输出json数据
            $this->api_200($data);
            exit;
        }

        /**
        *保存自定义竞标出价
         *
        */
        public function bidding_cus_price(){

            $dealer_id = $this->dealer_id;
            $order_id = $this->order_id;

            $price = I('post.price');//出价

            //数据验证
            if(!$dealer_id){
                AuctionException::make_throw('500001');
            }
            $dev_type = ($this->is_ios?2:1);

            $data = array();
            try {
                $handle = new THttpClient(C('WEAVER_URL'), 80, '/Auction/run');
                $transport = new TBufferedTransport($handle);
                $protocol = new TBinaryProtocol($transport);
                $auctionProtocol = new TMultiplexedProtocol($protocol, 'AuctionService');
                $auctionService = new AuctionServiceClient($auctionProtocol);

                $InParamsBidding                = new InParamsBidding();
                $InParamsBidding->dealerId      = $dealer_id;
                $InParamsBidding->orderId       = $order_id;
                $InParamsBidding->basePrice     = 0;
                $InParamsBidding->addPrice      = 0;
                $InParamsBidding->price         = $price;
                $InParamsBidding->deviceType    = $dev_type;
                $InParamsBidding->isAuto        = 0;
                $res = $auctionService->bidding($InParamsBidding);//return bool
                if(!$res){
                    $msg = '竞拍出价失败:order_id:'.$order_id.' dealer_id:'.$dealer_id.' price:'.$price;
                    trace($msg,'','DEBUG',true);
                    AuctionException::make_throw(700049);
                }
            } catch (TException $tx) {
                $code = $tx->getCode();
                $msg = $tx->getMessage();
                if(in_array($code,array('700047','700048'))){
                    $order = new AuOrder($order_id);
                    $order->thorw_to_app($dealer_id,$code);
                }else{
                    AuctionException::make_throw($code,$msg);
                }
            }

            //输出json数据
            $this->api_200($data);
            exit;
        }

        /**
         *  出价列表
         * @return mixed
         */
        public function get_bidding_price_log($ret=false, $limit='1000'){
            $dealer_id =  $this->dealer_id;
            $order_id = $this->order_id;
            $limit = I('request.page_size/d', $limit ? $limit : 1000);//程序内部调用，url调用

            $order = new AuOrder($order_id);
            $order_info = $order->detail();

            $redis = new PhpRedis();

            $arr = ['order_id'=>$this->order_id];
            $keyName = getRedisKeyByCode('REDIS_KEY','100010',$arr);
            $logs_list = $redis->get($keyName);
            if($logs_list){
                $logs_data = json_decode($logs_list,true);
                $logs_data = array_slice($logs_data, 0, $limit);
                $data = $this->get_format_logs($logs_data, $dealer_id, $order_info['bid_best_price']);
                if($ret){
                    return $data['list'];
                }
                $this->api_200($data);
            }
            $logs_data = $order->get_bidding_price_log();
            //缓存数据
            if(!empty($logs_data)){
                $redis->set($keyName, json_encode($logs_data, true), 60 * 60 * 24);
            }
            $logs_data = array_slice($logs_data, 0, $limit);
            $data = $this->get_format_logs($logs_data, $dealer_id, $order_info['bid_best_price']);
            //输出json数据
            if($ret){
                return $data['list'];
            }else{
                $this->api_200($data);
            }
        }
        /**
         * 处理出价记录
         * @param array $logs
         * @param int   $dealer_id
         * @param       $bid_best_price
        */
        private function get_format_logs($logs = array(), $dealer_id, $bid_best_price){
            foreach($logs as $key=>$log){
                $logs[$key]['price'] = strip_tags(format_money($log['after_price'])).'元';
                $logs[$key]['bid_max_price'] = $log['after_price'] > $bid_best_price ? '' : '温馨提示：当前竞拍最高价，未超过投标最高价。';
                if($log['dealer_id'] == $dealer_id && $log['is_auto'] == 1) {
                    $logs[$key]['dealer_name'] = '自己(智能报价)';
                }else if($log['dealer_id'] == $dealer_id && $log['is_auto'] == 0){
                    $logs[$key]['dealer_name'] = '自己(手动报价)';
                }else{
                    $logs[$key]['dealer_name'] = '其它商户';
                }
                $logs[$key]['state'] = $key==0 ? '1' : '2';
                $logs[$key]['time'] = $log['createtime'];
            }
            $data = array();
            $data['hint'] = $logs[0]['bid_max_price'];
            $data['list'] = $logs;
            return $data;
        }
        //添加/取消关注
        public function follow()
        {
            if($this->dealer_id<1)
                AuctionException::make_throw('500001');

            if($this->order_id<1)
                AuctionException::make_throw('700027');

            $d = new Dealer($this->dealer_id);
            //查询是否关注
            $is_follow = $d->is_follow($this->order_id);
            if($is_follow){//已关注
                $result = $d->remove_follow($this->order_id);
                $ret = false;
            }else{//未关注
                $result = $d->add_follow($this->order_id);
                $ret = true;
            }
            if(!$result){
                AuctionException::make_throw('100066');
            }
            $this->api_200($ret);
        }

        //-------------检测报告
        /**
         * 检测报告 - 车辆、车况信息
         * return json
         */
        public function title() {
            $report_title[] = $this->report->header();
            $report_title_info = array();
            if (array_filter($report_title)) {
                foreach ($report_title as $v) {
                    $report_title_info = $v;
                    $pointer_mileage = convert_mileage($v['pointer_mileage']) . '万公里';
                    $first_reg_date = date("Y年m月", strtotime($v['first_reg_date'])) . '初登';
                    $report_title_info['car_name'] = $v['app_model_show'];
                    $report_title_info['summery'] = $first_reg_date . '/' . $pointer_mileage . '/' . C('GEARBOX')[$v['gearbox']] . '/' . $v['plate_number'];
                    $report_title_info['car_no'] = $v['car_no'];
                    $report_title_info['check_date'] = date("Y年m月d日", strtotime($v['check_date']));
                    $report_title_info['checker'] = $v['checker'];
                    $report_title_info['checker_level'] = $v['checker_level'];
                    $report_title_info['composite_level'] = $v['composite_state'] . $v['acc_level'];
                    $report_title_info['desc'] = $v['composite_state_desc'] . $v['acc_level_desc'];
                    $report_title_info['desc_app'] = $v['composite_state_desc'] . $v['acc_level_desc'] . $v['history_state'];
                }
            }
            return $report_title_info;
        }

        /**
         * 检测报告 - 基本信息
         * return array
         */
        public function base_info() {
            $base = $this->report->app_base_info();
            $base_info = array();
            if ($base) {
                $base['first_reg_date']['value'] = date("Y年m月d日", strtotime($base['first_reg_date']['value'])) . '初登';
                $base['ex_factory_date']['value'] = date("Y年m月d日", strtotime($base['ex_factory_date']['value']));
                $base_info = $this->getObjArr($base);
            }
            return $base_info;
        }


        /**
         * 检测报告 - 手续信息
         * return json
         */
        public function procedure() {
            $procedure_info[] = $this->report->procedure();
            if (array_filter($procedure_info)) {
                foreach ($procedure_info as $pi) {
                    foreach ($pi as $k => $p) {
                        if ($p['value'] == '无' || $p['value'] == '未见') {
                            $pi[$k]['style'] = 1;
                        } else {
                            $pi[$k]['style'] = 0;
                        }
                    }
                }
                $pi_info = $this->getObjArr($pi);
            }
            return $pi_info;
        }

        /**
         * 检测报告 - 配置信息
         * return json
         */
        public function config() {
            $config_info[] = $this->report->configuration();
            if (array_filter($config_info)) {
                foreach ($config_info as $ci) {
                    foreach ($ci as $k => $c) {
                        if ($c['value'] == '无') {
                            $ci[$k]['style'] = 1;
                        } else {
                            $ci[$k]['style'] = 0;
                        }
                    }
                }
                $ci_info = $this->getObjArr($ci);
            }
            return $ci_info;
        }

        /**
         * 检测报告 - 工况及附件说明
         * return json
         */
        public function perform() {
            $perform_info = $this->report->get_app_perform($this->car_id);
            if ($perform_info) {
                $perform_info = $this->getObjArr($perform_info);
            }
            return $perform_info;
        }

        /**
         * 检测报告 - 基本照片
         * return json
         */
        public function base_pics() {
            $base_pics_info = $this->report->get_base_pics_app();
            return $base_pics_info;
        }

        /**
         * 转换报告信息为对象格式
         * @param type $arr
         * @return type
         */
        private function getObjArr($arr) {
            $i = 0;
            $arr_info = array();
            foreach ($arr as $va) {
                $arr_info[$i] = $va;
                $i++;
            }
            return $arr_info;
        }

        private function get_dm_by_degree(){
                $arr = array();
                foreach ($this->report->report['damage'] as $k => $value) {
                    foreach($value['urls'] as $v){
                        //$v['urls'] = array_pop($v['urls']);
                        switch ($v['dm_degree']) {
                            case '2':
                                $arr['light'][$k] = $value;
                                $arr['light'][$k]['position_cn'] = $value['cus_pos_name']?$value['cus_pos_name']:C('VISIBLE_DAMAGE_POSITION.' . $value['position']);
                                break;
                            case '3':
                                $arr['normal'][$k] = $value;
                                $arr['normal'][$k]['position_cn'] = $value['cus_pos_name']?$value['cus_pos_name']:C('VISIBLE_DAMAGE_POSITION.' . $value['position']);
                                break;
                            case '4':
                                $arr['serious'][$k] = $value;
                                $arr['serious'][$k]['position_cn'] = $value['cus_pos_name']?$value['cus_pos_name']:C('VISIBLE_DAMAGE_POSITION.' . $value['position']);
                                break;
                        }
                    }
                }
                return $arr;
        }
}